// api/order_api/order_list.go
package order_api

import (
	"github.com/gin-gonic/gin"
	"muziai-server/models"
	"muziai-server/models/ctype"
	"muziai-server/service/common"
	"muziai-server/utils/jwts"
	"muziai-server/utils/res"
)

type OrderListRequest struct {
	models.Page
	UserID    uint                `json:"userID" form:"userID"`
	Type      int8                `json:"type" form:"type" binding:"required,oneof=1 2"`
	No        string              `json:"no" form:"no"`
	PayStatus ctype.PayStatusType `json:"payStatus" form:"payStatus"`
	PaySource int8                `json:"paySource" form:"paySource"`
	IsDeleted bool                `json:"isDeleted" form:"isDeleted"` //true查被删除的， false 正常查询
}

type OrderListResponse struct {
	models.OrderModel
	UserNickname string `json:"userNickname"`
	UserAvatar   string `json:"userAvatar"`
}

func (OrderApi) OrderListView(c *gin.Context) {
	var cr OrderListRequest
	err := c.ShouldBindQuery(&cr)
	if err != nil {
		res.FailWithError(c, err)
		return
	}
	_claims, _ := c.Get("claims")
	claims := _claims.(*jwts.Claims)

	var unscoped bool
	if cr.Type == 2 {
		if claims.IsAuth() {
			res.FailWithMsg(c, "权限错误")
			return
		}
	}
	switch cr.Type {
	case 1:
		cr.UserID = claims.UserID
	case 2:
		unscoped = cr.IsDeleted
	}

	_list, count, _ := common.QueryList(models.OrderModel{
		UserID:    cr.UserID,
		No:        cr.No,
		PayStatus: cr.PayStatus,
		PaySource: cr.PaySource,
	}, common.Option{
		Page:     cr.Page,
		Likes:    []string{"no"},
		Preloads: []string{"UserModel"},
		Unscoped: unscoped,
		Sort:     "created_at desc",
	})
	var list = make([]OrderListResponse, 0)
	for _, model := range _list {
		list = append(list, OrderListResponse{
			OrderModel:   model,
			UserNickname: model.UserModel.Nickname,
			UserAvatar:   model.UserModel.Avatar,
		})
	}

	res.OkWithList(c, list, count)
}
